//
//  MyNetWorkHelper.swift
//  MyWidgetExtension
//
//  Created by shuininzuo on 2021/4/6.
//

import SwiftUI

// 需求分析中定义的两个字段
struct MyDIYWidgetModel {
    var title: String
    var urlScheme: String
}

struct MyNetWorkHelper {
    // 请求url(这里改成你自己的url地址，我这里是模拟网络请求，就随便写一个)
    static let url_str = "https:www.baidu.com"
    // 网络请求方法
    static func request(completion: @escaping (Array<MyDIYWidgetModel>) -> Void) {
        let url = URL.init(string: url_str)
        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            // 这里模拟网络请求造的假数据
            let models = modelFromJson()
            completion(models)
        }
        task.resume()
    }
    
    // 数据序列化（解析）
    fileprivate static func modelFromJson() -> Array<MyDIYWidgetModel> {
        var models: [MyDIYWidgetModel] = []
        
        let data = [["title": "快捷选车", "urlScheme": "a"],
                    ["title": "销量排行", "urlScheme": "b"],
                    ["title": "厂家直购", "urlScheme": "c"],
                    ["title": "汽车保养", "urlScheme": "a"]]
        
        for item in data {
            var title = ""
            var urlScheme = ""
            if let n = item["title"] {
                title = n
            }
            if let n = item["urlScheme"] {
                urlScheme = n
            }
            let model = MyDIYWidgetModel(title: title, urlScheme: urlScheme)
            models.append(model)
        }
        return models
    }
}
